package ils.web.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import ils.domain.catalog.model.Book;
import ils.services.CatalogService;
import ils.util.SpringUtil;
import org.apache.struts2.interceptor.SessionAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class AddBookAction extends ActionSupport implements SessionAware, Preparable
{
    private static final Logger logger = LoggerFactory.getLogger(AddBookAction.class);
    private Map<String, Object> session;
    private CatalogService catalogService;
    private Book book;
    private String topics;
    
    public String execute() throws Exception
    {
        logger.debug("entering AddBookAction");
        if(book == null) return INPUT;
        if(topics != null) book.setTopics(parseTopics(topics));
        catalogService.addBook(book);
        logger.debug("exiting AddBookAction");
        return SUCCESS;
    }
    private List<String> parseTopics(String input)
    {
        String[] topics = input.split(",");
        return Arrays.asList(topics);
    }
    
    @Override
    public void setSession(Map<String, Object> arg0)
    {
        this.session = arg0;
    }

    public void setCatalogService(CatalogService catalogService)
    {
        this.catalogService = catalogService;
    }

    public Book getBook()
    {
        return book;
    }

    public void setBook(Book book)
    {
        this.book = book;
    }

    public String getTopics() {
        return topics;
    }

    public void setTopics(String topics) {
        this.topics = topics;
    }

    @Override
    public void prepare() throws Exception {
        catalogService = (CatalogService) SpringUtil.getApplicationContext().getBean("catalogService");
    }
}
